﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Text.RegularExpressions;

namespace Game.Utilities.Chat
{
    public static class ChatFilter
    {
        private static readonly object lockLoadBadWords = new object();

        private const string RegexAcceptChars = @"[^aáàảãạăắằẳẵặâấầẩẫậđeéèẻẽẹêếềểễệiíìỉĩịoóòỏõọôốồổỗộơớờởỡợuúùủũụưứừửữựyýỳỷỹỵAÁÀẢÃẠĂẮẰẲẴẶÂẤẦẨẪẬĐEÉÈẺẼẸÊẾỀỂỄỆIÍÌỈĨỊOÓÒỎÕỌÔỐỒỔỖỘƠỚỜỞỠỢUÚÙỦŨỤƯỨỪỬỮỰYÝỲỶỸỴ\w\s\d]+";
        private static List<string> _badWords;
        private static List<string> _badLinks;

        public static string RemoveUnAcceptChars(string input)
        {
            Regex regx = new Regex(RegexAcceptChars, RegexOptions.Compiled | RegexOptions.IgnoreCase);

            string output = regx.Replace(input, "*");

            return output;
        }

        public static string RemoveBadWords(string input)
        { 
            if (_badWords == null || _badWords.Count < 1)
            {
                lock (lockLoadBadWords)
                {
                    string assemblyFolder = Path.GetDirectoryName(new Uri(Assembly.GetExecutingAssembly().CodeBase).LocalPath);//Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
                    string filePath = Path.Combine(assemblyFolder, "Chat\\Data\\badwords.txt");
                    try
                    {
                        if (File.Exists(filePath))
                        {
                            string[] allText = File.ReadAllLines(filePath);

                            _badWords = new List<string>(allText);
                        }
                    }
                    catch (Exception)
                    {
                    }
                }
            }

            if (_badWords != null)
            {
                int bwLength = _badWords.Count;
                for (int i = 0; i < bwLength; i++)
                {
                    input = input.Replace(_badWords[i], "***", StringComparison.OrdinalIgnoreCase);
                }
            }

            return input;
        }
    }
}